<!-- src/components/Calendar/views/MonthView.vue -->
<template>
  <div class="month-view">
    <div class="month-header">
      <div class="week-day" v-for="day in weekDaysFull" :key="day">{{ day }}</div>
    </div>
    <div class="month-grid">
      <div 
        class="month-grid-day" 
        v-for="day in monthDays" 
        :key="`${day.fullDate.getTime()}`"
        :class="{
          'other-month': !day.isCurrentMonth,
          'today': day.isToday,
          'selected': day.isSelected
        }"
        @click="handleDayClick(day, $event)"
      >
        <!-- 调整日期和农历位置为顶部居中 -->
        <div class="day-info">
          <div class="day-number">{{ day.date }}</div>
          <div class="day-lunar">{{ day.lunar }}</div>
        </div>
        
        <!-- 任务按钮列表 - 显示该日期的所有任务 -->
        <div 
          v-for="(buttonInfo, index) in getTaskButtonsForDay(day.fullDate)"
          :key="buttonInfo.cardId || buttonInfo.tempKey || index"
          :class="[
            'task-button',
            {
              'temp-button': buttonInfo.isTemp,
              'task-button--task': buttonInfo.kind === 'task'
            }
          ]"
          :style="buttonInfo.style"
          @click.stop="handleTaskButtonClick(buttonInfo, day, $event)"
        >
          {{ buttonInfo.title }}
        </div>
      </div>
    </div>

    <!-- 蒙板 -->
    <div 
      v-if="cardStore.showBaseCard || cardStore.showDetailCard" 
      class="overlay" 
      @click="handleOverlayClick"
    ></div>

    <!-- BaseCard 组件 -->
    <BaseCard
      v-if="cardStore.showBaseCard"
      :key="`basecard-month-${baseCardKey}`"
      :position="cardStore.adjustedBaseCardPosition()"
      :selected-date="cardStore.currentSelectedDate"
      @close="handleCloseBaseCard"
      @drag="handleBaseCardDrag"
      @save="handleSaveCard"
    />

    <!-- 详情卡片组件 -->
    <div 
      v-if="cardStore.showDetailCard && cardStore.currentDetailCard"
      class="detail-card-container"
      :style="detailCardStyle"
    >
      <ActivityCard 
        v-if="cardStore.currentDetailCard.type === 'activity'" 
        :card-data="cardStore.currentDetailCard as any"
        :position="cardStore.adjustedDetailCardPosition()"
        @close="handleCloseDetailCard"
        @delete="handleDeleteActivityCard"
        @edit="handleEditActivityCard"
      />
      <MissionCard 
        v-else-if="cardStore.currentDetailCard.type === 'task'" 
        :card-data="cardStore.currentDetailCard as any"
        :position="cardStore.adjustedDetailCardPosition()"
        @close="handleCloseDetailCard"
        @delete="handleDeleteMissionCard"
        @edit="handleEditMissionCard"
        @update:cardData="handleMCardUpdate"
      />
    </div>

    <!-- 编辑活动卡片组件 -->
    <EditACard
      v-if="showEditACard && editingACard"
      :card-data="editingACard"
      @close="handleEditACardClose"
      @update:cardData="handleACardUpdate"
      @delete="handleDeleteActivityCard"
    />

    <!-- 编辑任务卡片组件 -->
    <EditMCard
      v-if="showEditMCard && editingMCard"
      :card-data="editingMCard"
      @close="handleEditMCardClose"
      @update:cardData="handleMCardUpdate"
      @delete="handleDeleteMissionCard"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import { useCardStore } from '@/store/card'
import type { DayData } from '@/types/timeData'
import type { activityCard, missionCard } from '@/types/card'
import BaseCard from '@/components/Cards/BaseCard.vue'
import ActivityCard from '@/components/Cards/ActivityCard.vue'
import MissionCard from '@/components/Cards/MissionCard.vue'
import EditACard from '@/components/Cards/EditACard.vue'
import EditMCard from '@/components/Cards/EditMCard.vue'
import { ElMessage } from 'element-plus'

interface Props {
  monthDays: any[]
}

const props = defineProps<Props>()
const emit = defineEmits(['select-month-date'])

const weekDaysFull = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']

type CalendarButtonKind = 'activity' | 'task' | 'temp'

// 使用 card store
const cardStore = useCardStore()

// 编辑卡片状态
const showEditACard = ref(false)
const editingACard = ref<activityCard | null>(null)
const showEditMCard = ref(false)
const editingMCard = ref<missionCard | null>(null)

// BaseCard 的 key，用于强制重新创建组件（与周视图和日视图保持一致）
const baseCardKey = ref(0)

// 计算详情卡片样式
const detailCardStyle = computed(() => {
  const position = cardStore.adjustedDetailCardPosition()
  return {
    left: `${position.x}px`,
    top: `${position.y}px`
  }
})

// 处理日期点击
const handleDayClick = (day: DayData, event: MouseEvent) => {
  emit('select-month-date', day)
  
  // 显示BaseCard（强制新建，允许同一天多个卡片）
  const dayElement = event.target as HTMLElement
  if (dayElement) {
    const rect = dayElement.getBoundingClientRect()
    cardStore.openBaseCard(day.fullDate, {
      x: rect.left,
      y: rect.bottom + 5
    }, true) // forceNew = true，允许同一天多个卡片
  }
}

// 获取该日期的所有任务按钮
const getTaskButtonsForDay = (date: Date) => {
  const buttons: Array<{
    cardId?: string
    tempKey?: string
    title: string
    style: { bottom?: string; left?: string; right?: string; width?: string }
    isTemp: boolean
    card: activityCard | missionCard | null
    kind: CalendarButtonKind
  }> = []
  
  const dateString = date.toDateString()
  
  // 获取该日期的所有活动卡片（根据显示状态过滤）
  let activityCards = cardStore.getActivityCardsForDate(date)
  if (!cardStore.showActivityCards) {
    activityCards = []
  }
  
  // 获取该日期的所有任务卡片（根据显示状态过滤）
  let missionCards = cardStore.getMissionCardsForDate(date)
  missionCards = missionCards.filter(card => cardStore.shouldShowMissionCard(card))
  
  // 合并所有卡片并按创建时间排序（最新的在前）
  const allCards = [...activityCards, ...missionCards] as (activityCard | missionCard)[]
  allCards.sort((a, b) => {
    const timeA = a.createdAt ? new Date(a.createdAt).getTime() : 0
    const timeB = b.createdAt ? new Date(b.createdAt).getTime() : 0
    return timeB - timeA // 倒序，最新的在前
  })
  
  // 为每个卡片创建按钮
  // 按钮高度24px + 间距2px = 26px（减少2px）
  const buttonHeight = 24
  const buttonGap = 2
  const baseBottom = 14 // 原本4px，上移10px用于验证（4 + 10 = 14）
  
  allCards.forEach((card, index) => {
    const kind: CalendarButtonKind = card.type

    buttons.push({
      cardId: card.id,
      title: card.title || '(无标题)',
      style: {
        bottom: `${baseBottom + index * (buttonHeight + buttonGap)}px`,
        left: '4px',
        right: '4px'
      },
      isTemp: false,
      card,
      kind
    })
  })
  
  // 处理临时按钮（未保存的卡片）
  if (cardStore.tempButtonDate && cardStore.tempButtonDate.toDateString() === dateString) {
    buttons.push({
      tempKey: `temp-${dateString}`,
      title: cardStore.getCardTitleForDate(date) || '(无标题)',
      style: {
        bottom: `${baseBottom + allCards.length * (buttonHeight + buttonGap)}px`,
        left: '4px',
        right: '4px'
      },
      isTemp: true,
      card: null,
      kind: 'temp'
    })
  }
  
  return buttons
}

// 处理任务按钮点击
const handleTaskButtonClick = (
  buttonInfo: {
    cardId?: string
    tempKey?: string
    title: string
    isTemp: boolean
    card: activityCard | missionCard | null
  },
  day: DayData,
  event: MouseEvent
) => {
  const buttonElement = event.target as HTMLElement
  if (buttonElement) {
    const rect = buttonElement.getBoundingClientRect()
    
    // 如果有关联的卡片，打开详情卡片
    if (buttonInfo.cardId && buttonInfo.card) {
      cardStore.openDetailCard(buttonInfo.card, {
        x: rect.left,
        y: rect.bottom + 5
      })
    } else if (buttonInfo.isTemp) {
      // 临时按钮，打开新建卡片
      cardStore.openBaseCard(day.fullDate, {
        x: rect.left,
        y: rect.bottom + 5
      }, true)
    }
  }
}


// 处理保存卡片
const handleSaveCard = (cardData: activityCard | missionCard) => {
  try{
    if(cardData.type === 'activity') cardStore.saveACard(cardData)
    else if(cardData.type === 'task') cardStore.saveMCard(cardData)
    ElMessage.success('保存成功')
  } catch (error) {
    ElMessage.error('保存失败')
    console.log('保存卡片失败', error)
  }
  
}

// 处理蒙板点击
const handleOverlayClick = (event: MouseEvent) => {
  if (event.target === event.currentTarget) {
    handleCloseBaseCard()
    handleCloseDetailCard()
  }
}

// 关闭 BaseCard
const handleCloseBaseCard = () => {
  cardStore.closeBaseCard()
}

// 关闭A/MCard
const handleCloseDetailCard = () => {
  cardStore.closeDetailCard()
}

// 删除ACard
const handleDeleteActivityCard = async (cardId: string) => {
  try {
    await cardStore.deleteACard(cardId)
    ElMessage.success(`活动卡片 ${cardId} 成功删除`)
    handleCloseDetailCard()

    if (editingACard.value && editingACard.value.id === cardId) {
      handleEditACardClose()
    }
  } catch(error) {
    console.log('删除活动卡片失败', error)
    ElMessage.error('删除活动卡片失败')
  }
  
}

// 编辑ACard
const handleEditActivityCard = (card: activityCard) => {
  ElMessage.info('编辑ACard')
  handleCloseDetailCard()
  editingACard.value = {...card} // 创建副本
  showEditACard.value = true
}

// 删除MCard
const handleDeleteMissionCard = async (cardId: string) => {
  try {
    await cardStore.deleteMCard(cardId)
    ElMessage.success(`任务卡片 ${cardId} 删除成功`)
    handleCloseDetailCard()

    if (editingMCard.value && editingMCard.value.id === cardId) {
      handleEditMCardClose()
    }
  } catch (error) {
    console.error('删除任务卡片失败:', error)
    ElMessage.error('删除任务卡片失败')
  }
}

// 编辑MCard
const handleEditMissionCard = (card: missionCard) => {
  handleCloseDetailCard()
  editingMCard.value = {...card} // 创建副本
  showEditMCard.value = true
}

// 处理 BaseCard 拖拽
const handleBaseCardDrag = (position: { x: number; y: number }) => {
  cardStore.updateBaseCardPosition(position)
}

// 处理EditACard关闭
const handleEditACardClose = () => {
  showEditACard.value = false
  editingACard.value = null
}

// 处理ACard更新
// 注意这里又更新又保存
const handleACardUpdate = async (updatedCard: activityCard) => {
  try {
    // 使用store的saveACard方法更新卡片
    await cardStore.saveACard(updatedCard)
    
    ElMessage.success('活动更新成功')
    
    // 关闭编辑卡片
    handleEditACardClose()
    
    // 如果需要，可以在这里添加其他逻辑，比如刷新卡片列表等
    
  } catch (error) {
    console.error('更新活动卡片失败:', error)
    ElMessage.error('更新活动卡片失败')
  }
}

// 处理EditMCard关闭
const handleEditMCardClose = () => {
  showEditMCard.value = false
  editingMCard.value = null
}

// 处理MCard更新
// 注意这里又更新又保存
const handleMCardUpdate = async (updatedCard: missionCard) => {
  try {
    // 使用store的saveMCard方法更新卡片（会自动同步到任务列表）
    const savedCard = await cardStore.saveMCard(updatedCard)
    
    // 如果当前显示的是详情卡片，更新详情卡片的数据
    if (cardStore.currentDetailCard && cardStore.currentDetailCard.id === savedCard.id) {
      cardStore.currentDetailCard = savedCard
    }
    
    ElMessage.success('任务更新成功')
    
    // 关闭编辑卡片
    handleEditMCardClose()
    
  } catch (error) {
    console.error('更新任务卡片失败:', error)
    ElMessage.error('更新任务卡片失败')
  }
}
</script>

<style scoped>
.month-view {
  height: 95%;
  display: flex;
  flex-direction: column;
  position: relative;
}

.month-header {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  background: #f8f9fa;
  border-bottom: 1px solid #e0e0e0;
}

.week-day {
  padding: 16px 8px;
  text-align: center;
  font-weight: 600;
  color: #333;
  border-right: 1px solid #e0e0e0;
}

.month-grid {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  grid-template-rows: repeat(6, 1fr);
  overflow-y: auto;
  scrollbar-width: none;
}

.month-grid-day {
  border-right: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
  padding: 8px;
  cursor: pointer;
  transition: background 0.2s ease;
  position: relative;
  min-height: 80px;
}

.month-grid-day:hover {
  background: #f8f9fa;
}

.month-grid-day.other-month {
  color: #ccc;
  background: #f9f9f9;
}

.month-grid-day.today {
  background: #e3f2fd;
}

.month-grid-day.selected {
  background: #1976d2;
  color: white;
}

/* 调整日期和农历位置为顶部居中 */
.day-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  text-align: center;
  margin-top: 4px;
}

.day-number {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 2px;
}

.day-lunar {
  font-size: 12px;
  color: #666;
}

.month-grid-day.selected .day-lunar {
  color: rgba(255, 255, 255, 0.8);
}

.month-grid-day.other-month .day-lunar {
  color: #ccc;
}

/* 任务按钮样式 - 调整为深绿色 */
.task-button {
  position: absolute;
  bottom: 14px; /* 原本4px，上移10px用于验证 */
  left: 4px;
  right: 4px;
  height: 24px; /* 固定高度，确保垂直堆叠时对齐（减少2px） */
  background: #2e7d32; /* 深绿色 */
  color: white;
  padding: 2px 6px; /* 减少2px */
  border-radius: 4px;
  font-size: 12px;
  text-align: center;
  cursor: pointer;
  transition: background 0.2s ease;
  z-index: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: flex;
  align-items: center;
  justify-content: center;
}

.task-button:hover {
  background: #1b5e20; /* 更深的绿色 */
}

/* 临时按钮样式 */
.temp-button {
  background: #ff9800; /* 橙色表示临时状态 */
}

.temp-button:hover {
  background: #f57c00; /* 更深的橙色 */
}

.task-button--task {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  padding: 2px 8px;
  min-height: 24px;
  right: auto;
}

.task-button--task::before {
  content: '\2713';
  font-weight: 600;
}

/* 蒙板样式 */
.overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: transparent;
  z-index: 999;
}

/* 详情卡片容器样式 */
.detail-card-container {
  position: fixed;
  width: 340px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  border: 1px solid #e0e0e0;
  z-index: 1000;
}

.detail-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f5f5f5;
  border-bottom: 1px solid #e0e0e0;
  border-radius: 8px 8px 0 0;
}

.detail-card-title {
  font-weight: 600;
  color: #333;
}

.detail-card-close {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #666;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: background 0.2s ease;
}

.detail-card-close:hover {
  background: #e0e0e0;
  color: #333;
}

.detail-card-content {
  padding: 16px;
  max-height: 400px;
  overflow-y: auto;
}
</style>